<template>
  <el-dialog
    :title="$t('m.EMPLOYEE_DETAILS')"
    custom-class="employee-dialog"
    :close-on-click-modal="false"
    :modal="false"
    :visible.sync="open"
    :before-close="handleClose"
  >
    <el-scrollbar class="employee-scrollbar" wrap-class="employee-scrollbar__wrap">
      <el-form
        ref="form"
        :class="readonly ? 'detail' :'edit'"
        label-suffix=":"
        size="small"
        :rules="rules"
        :model="formData"
        hide-required-asterisk
      >
        <div class="person-item">
          <div class="person-info">
            <el-form-item :label="$t('m.NAME')" prop="realName">
              <el-input v-model="formData.realName" :readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.SEX')" prop="sex">
              <el-select
                v-model="formData.sex"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option
                  v-for="opt in dict.sexOptions"
                  :key="opt.value"
                  :label="$t('m.dict.sex')[opt.value]"
                  :value="opt.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('m.PRIORITY')" prop="isUrgent">
              <el-select
                v-model="formData.isUrgent"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option key="0" label="0" value="0"></el-option>
                <el-option key="1" label="1" value="1"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="头像设置" prop="realName">
              <img src="../../assets/images/idle.png"  />
            </el-form-item>-->
          </div>
          <!-- <el-upload
            class="person-avator"
            v-show="submitBtn || formData.ico"
            :headers="uploadHeaders"
            :action="actionUrl"
            :accept="acceptType"
            :disabled="!submitBtn"
            :show-file-list="false"
            :on-success="onSuccess"
          >
            <img :src="formData.localUrl || formData.ico || defaultImg" />
          </el-upload>-->
        </div>
        <el-divider class="default-divider"></el-divider>
        <el-form-item :label="$t('m.GROUP')" prop="group" class="form-item-group">
          <div class="group-item" v-for="(item, index) in formData.group" :key="item.groupID">
            <svg-icon
              icon-class="remove"
              v-if="!readonly"
              @click="removeList(formData.group,item.groupID, index,'groupTree')"
            ></svg-icon>
            <el-input :value="item.groupName || getGroupName(item)" readonly></el-input>
          </div>
          <div class="group-item add" v-if="!readonly">
            <svg-icon icon-class="plus" @click="addGroup()"></svg-icon>
            <label class="add-label" @click="addGroup()">{{$t('m.ADD_GROUP_BELONGS')}}</label>
            <span class="valid-rule">{{groupValid}}</span>
          </div>
        </el-form-item>
        <el-divider class="default-divider"></el-divider>
        <el-form-item :label="$t('m.DUTY')" prop="dutyName" class="form-item-group">
          <div class="group-item" v-for="(item, index) in formData.dutyID" :key="item">
            <svg-icon
              icon-class="remove"
              v-if="!readonly"
              @click="removeList(formData.dutyID, item, index, 'dutyTree')"
            ></svg-icon>
            <!-- <el-input :value="item" readonly></el-input> -->
            <el-select
              v-model="formData.dutyID[index]"
              popper-class="default-select-popper"
              :disabled="disabled"
            >
              <el-option
                v-for="opt in dutyOption"
                :key="opt.dutyID"
                :label="opt.dutyName"
                :value="opt.dutyID"
              ></el-option>
            </el-select>
          </div>
          <div class="group-item add" v-if="!readonly">
            <svg-icon icon-class="plus" @click="addDuty()"></svg-icon>
            <label class="add-label" @click="addDuty()">{{$t('m.ADD_DUTY')}}</label>
          </div>
        </el-form-item>
        <el-divider class="default-divider"></el-divider>
        <el-form-item :label="$t('m.TEL')" class="form-item-group">
          <div class="group-item" v-for="(item, index) in formData.device" :key="index">
            <div class="svg-button">
              <svg-icon
                icon-class="remove"
                v-if="!readonly"
                @click="removeList(formData.device, '', index, 'tel')"
              ></svg-icon>
            </div>
            <el-form-item :prop="`device[${index}].deviceType`">
              <el-select
                v-model="item.deviceType"
                popper-class="default-select-popper"
                :disabled="disabled"
              >
                <el-option
                  v-for="opt in dict.deviceTypeOptions"
                  :key="opt.value"
                  :label="$t('m.dict.deviceTypeOptions')[opt.value]"
                  :value="opt.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :prop="`device[${index}].deviceTel`" :rules="telRules.deviceTel">
              <el-input
                style="margin-left:10px;"
                v-model="item.deviceTel"
                @input="changeInput($event)"
                :readonly="!submitBtn"
              ></el-input>
            </el-form-item>
            <el-form-item prop="defaultNo">
              <el-radio
                class="set-defaultNo"
                v-show="(submitBtn) || (!submitBtn && formData.defaultNo === item.deviceTel)"
                v-model="formData.defaultNo"
                :label="item.deviceTel"
              >{{$t('m.DEFAULT_NO')}}</el-radio>
              <!-- 默认号码 -->
            </el-form-item>
          </div>
          <div class="group-item add" v-if="!readonly">
            <svg-icon icon-class="plus" @click="addTel()"></svg-icon>
            <label class="add-label" @click="addTel()">{{$t('m.ADD_TEL')}}</label>
            <span class="valid-rule">{{telValid}}</span>
          </div>
        </el-form-item>
        <el-divider class="default-divider" v-show="false"></el-divider>
        <el-form-item :label="$t('m.CAMERA')" prop="videoID" class="form-item-group" v-show="false">
          <div class="group-item" v-for="(item, index) in formData.videoID" :key="item">
            <svg-icon
              icon-class="remove"
              v-if="!readonly"
              @click="removeList(formData.videoID, item, index, 'videoTree')"
            ></svg-icon>
            <el-input :value="getVideoName(item)" readonly></el-input>
          </div>
          <div class="group-item add" v-if="!readonly">
            <svg-icon icon-class="plus" @click="addVideo()"></svg-icon>
            <label class="add-label" @click="addVideo()">{{$t('m.ADD_CAMERA')}}</label>
          </div>
        </el-form-item>
        <el-divider class="default-divider"></el-divider>
        <div style="margin: 5px 0;">
          <el-form-item :label="$t('m.GPS_NUMBER')" prop="gpsBH">
            <el-input v-model="formData.gpsBH" :readonly="readonly"></el-input>
          </el-form-item>
        </div>
        <!-- <div>
          <el-form-item label="按键值" prop="keyNumber">
            <el-input v-model="formData.keyNumber" :readonly="readonly"></el-input>
          </el-form-item>
        </div>-->
        <div class="remark">
          <el-form-item :label="$t('m.REAMRKS')" prop="remark">
            <el-input type="textarea" :rows="3" v-model="formData.remark" :readonly="readonly"></el-input>
          </el-form-item>
        </div>
      </el-form>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer">
      <el-button
        @click="handleEdit(submitBtn)"
        :disabled="commitDisabled"
        size="small"
      >{{ submitBtn ? $t('m.CONFIRM') : $t('m.EDIT') }}</el-button>
      <el-button @click="handleClose" size="small">{{$t('m.CANCEL')}}</el-button>
    </div>
    <!-- 组选择 -->
    <div class="default-select-tree groupTree" v-show="showTree === 'groupTree'">
      <el-scrollbar class="tree-scrollbar" wrap-class="tree-scrollbar__wrap">
        <el-tree
          :data="userGroupTreeData"
          icon-class="el-icon-arrow-right"
          node-key="nid"
          highlight-current
          @check-change="groupCheckChange"
          :filter-node-method="groupFilter"
          show-checkbox
          check-strictly
          ref="groupTree"
        ></el-tree>
      </el-scrollbar>
    </div>
    <!-- 职位选择 -->
    <div class="default-select-tree dutyTree" v-show="showTree === 'dutyTree'">
      <el-scrollbar class="tree-scrollbar" wrap-class="tree-scrollbar__wrap">
        <el-tree
          :data="dutyData"
          :props="dutyProps"
          icon-class="el-icon-arrow-right"
          node-key="dutyID"
          highlight-current
          @check-change="dutyCheckChange"
          show-checkbox
          check-strictly
          ref="dutyTree"
        ></el-tree>
      </el-scrollbar>
      <el-button size="small" @click="showVideoGroupTree = false">{{$t('m.CONFIRM')}}</el-button>
    </div>
    <!-- 摄像头选择 -->
    <div class="default-select-tree videoTree" v-show="showTree === 'videoTree'">
      <el-scrollbar class="tree-scrollbar" wrap-class="tree-scrollbar__wrap">
        <el-tree
          :data="videoTreeData"
          class="is-leaf-checkbox"
          icon-class="el-icon-arrow-right"
          node-key="nid"
          highlight-current
          @check-change="videoCheckChange"
          show-checkbox
          :props="videoProps"
          check-strictly
          ref="videoTree"
        ></el-tree>
      </el-scrollbar>
    </div>
  </el-dialog>
</template>

<script>
import { dataflow } from '@/api/data'
import { mapGetters } from 'vuex'
import { getDuty } from '@/api/data'
export default {
  props: {
    open: Boolean,
    title: String,
    formData: Object,
    editFlag: Boolean, //进入时判断是否直接编辑页面标识
  },

  computed: {
    ...mapGetters([
      'dict',
      'groupMap',
      'videoMap',
      'videoTreeData',
      'userGroupTreeData',
      'videoNidMap',
    ]),
    rules() {
      return {
        realName: [
          {
            required: true,
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        sex: [
          {
            required: true,
            // message: '请选择性别',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
      }
    },
    telRules() {
      return {
        deviceTel: [
          {
            required: true,
            // message: '号码不能为空',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur',
          },
        ],
        deviceType: [
          {
            required: true,
            // message: '请选择号码类型',
            message: this.$t('m.tip.CAN_NOT_BE_EMPTY'),
            trigger: 'blur,change',
          },
        ],
      }
    },
  },
  data() {
    return {
      // defaultImg: require('@/assets/images/add-picture.png'),
      defaultImg: require('@/assets/images/idle.png'),
      readonly: true, // 详情时只读
      disabled: true,
      submitBtn: false,
      checkedPerson: [],
      videoProps: {
        disabled: (data, node) => {
          node.isLeaf = data.children ? false : true
          return !node.isLeaf
        },
      },
      dutyProps: {
        label: 'dutyName',
      },
      uploadHeaders: {
        ContentType: 'multipart/form-data',
        Authorization: sessionStorage.getItem('tokenSign'),
      },
      actionUrl: '/materials/person/imgUpload',
      acceptType: 'image/*', //图片格式

      groupValid: '', // 组校验信息
      telValid: '',
      commitDisabled: false, // 提交按钮

      dutyData: [
        { dutyID: '1', dutyName: '总经理' },
        { dutyID: '2', dutyName: '副总经理' },
        { dutyID: '3', dutyName: '科长' },
        { dutyID: '4', dutyName: 'test' },
      ], // 职务数据

      showTree: '',
      dutyOption: [],
    }
  },
  watch: {
    'formData.group'(newValue) {
      if (newValue.length > 0) {
        this.groupValid = ''
      }
    },
    'formData.device'(newValue) {
      if (newValue.length === 0) {
        this.formData.defaultNo = ''
      } else if (newValue.length === 1 && newValue[0].deviceTel) {
        this.formData.defaultNo = newValue[0].deviceTel
      }
    },
  },
  methods: {
    //上报处理
    // event(e) {
    //   let _this = this
    //   console.log('event', e.type, e)
    //   switch (e.type) {
    //     case 'EmployeeMod':
    //       if (e.result == 'succ') {
    //         console.log('修改成功')
    //         //刷新数据
    //         _this.$emit('handleUpdateData')
    //       } else {
    //         _this.$message.waring('修改失败')
    //       }
    //       break
    //     default:
    //       break
    //   }
    // },
    // 文件上传成功
    onSuccess(response, file) {
      console.log('onSuccess', response)
      let URL
      if (window.createObjectURL != undefined) {
        // basic
        URL = window.createObjectURL(file.raw)
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        URL = window.URL.createObjectURL(file.raw)
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        URL = window.webkitURL.createObjectURL(file.raw)
      }
      this.formData.localUrl = URL
      this.formData.ico = response.true
    },
    // 组选择框改变
    groupCheckChange(node, checked) {
      if (checked) {
        if (!this.formData.group.some((g) => g.groupID === node.obj.groupID)) {
          this.formData.group.push({
            groupID: node.obj.groupID,
            groupName: node.obj.groupName,
            orderNO: Number(this.formData.group.length + 1),
          })
        }
      } else {
        let index = this.formData.group.findIndex(
          (g) => g.groupID === node.obj.groupID
        )
        if (index !== -1) this.formData.group.splice(index, 1)
      }
    },
    // 职员选择框改变
    dutyCheckChange(node, checked) {
      if (checked) {
        if (!this.formData.dutyName.some((name) => name === node.dutyName)) {
          this.formData.dutyName.push(node.dutyName)
        }
      } else {
        let index = this.formData.dutyName.findIndex(
          (item) => item === node.dutyName
        )
        if (index !== -1) this.formData.dutyName.splice(index, 1)
      }
    },
    // 摄像头选择框改变
    videoCheckChange(node, checked) {
      if (this.formData.videoID == undefined) {
        this.formData.videoID = []
      }
      if (checked) {
        if (
          !this.formData.videoID.some((videoID) => videoID === node.obj.videoID)
        ) {
          this.formData.videoID.push(node.obj.videoID)
        }
      } else {
        let index = this.formData.videoID.findIndex(
          (videoID) => videoID === node.obj.videoID
        )
        if (index !== -1) this.formData.videoID.splice(index, 1)
      }
    },
    // 组过滤
    groupFilter(value, data, node) {
      return data.obj.groupType !== 'dispatchgroup'
    },
    // 添加组按钮
    addGroup() {
      this.showTree = 'groupTree'
      this.$nextTick(() => {
        this.$refs.groupTree.filter()
        this.formData.group.forEach((item) => {
          let node = this.groupMap.get(item.groupID)
          if (node) {
            this.$refs.groupTree.setChecked(node.nid, true)
          }
        })
      })
    },
    // 添加职务按钮
    addDuty() {
      if (this.formData.dutyID === undefined) {
        this.formData.dutyID = []
      }
      const length = this.formData.dutyID.length
      this.formData.dutyID[length] = this.dutyOption[0].dutyID
      this.$set(this.formData.dutyID, length, this.dutyOption[0].dutyID)
      this.$forceUpdate()
    },
    // 添加号码按钮
    addTel() {
      const length = this.formData.device.length
      this.formData.device.push({
        deviceTel: '',
        orderNO: length + 1,
        deviceType: 'office',
      })
    },
    // 添加摄像头按钮
    addVideo() {
      this.showTree = 'videoTree'
      this.$nextTick(() => {
        this.formData.videoID.forEach((videoID) => {
          let nids = this.videoNidMap.get(videoID)
          if (nids) {
            this.$refs.videoTree.setChecked(nids[0], true)
          }
        })
      })
    },
    // 获取组名称
    getGroupName(item) {
      let group = this.groupMap.get(item.groupID)
      if (group) item.groupName = group.obj.groupName
      return item.groupName || ''
    },
    // 获取摄像头名称
    getVideoName(videoID) {
      let video = this.videoMap.get(videoID)
      // if (video) item.groupName = group.obj.groupName;
      return video ? video.videoName : ''
    },
    // 删除按钮
    removeList(list, id, index, treeRef) {
      list.splice(index, 1)
      this.$nextTick(() => {
        switch (treeRef) {
          case 'videoTree':
            let nids = this.videoNidMap.get(id)
            if (nids) {
              this.$refs[treeRef].setChecked(nids[0], false)
            }
            break
          case 'groupTree':
            let node = this.groupMap.get(id)
            if (node) {
              this.$refs[treeRef].setChecked(node.nid, false)
            }
            break
          case 'dutyTree':
            if (this.formData.dutyID.splice(index, 1)) this.$forceUpdate()
            break
          case 'tel':
            if (list.length === 0) this.formData.defaultNo = ''
            else if (list.length === 1 && list[0].deviceTel)
              this.formData.defaultNo = list[0].deviceTel
            break
        }
      })
    },
    // 按钮是否禁用
    toolBtnDistabled() {
      if (this.formData.type === 'label') {
        return this.formData.personList.length > 0
      }
      return false
    },
    //编辑
    handleEdit(submitBtn) {
      if (!submitBtn) {
        this.readonly = false
        this.disabled = false
        this.submitBtn = true
      } else {
        let form = this.formData
        this.commitDisabled = true
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (form.group.length === 0) {
              this.commitDisabled = false
              this.groupValid = '请选择组'
              return
            }
            if (form.device.length === 0) {
              this.commitDisabled = false
              this.telValid = '请添加号码'
              return
            }
            if (!form.defaultNo) {
              this.commitDisabled = false
              this.telValid = '请选择默认号码'
              return
            }
            let num = false
            form.device.forEach((e) => {
              if (e.deviceTel == form.defaultNo) {
                num = true
              }
            })
            if (!num) {
              this.commitDisabled = false
              this.telValid = '请选择默认号码'
              return
            }
            if (form.defaultNo) form.videoID = form.videoID
            // console.log('handleEdit', JSON.stringify(form))
            // 提交表单
            if (form.employeeID) {
              SDK.employeeMod(form)
                .then((res) => {
                  this.handleClose()
                  this.$store.dispatch('initUser')
                  this.$emit('clearTableData')
                })
                .catch((err) => {
                  console.log(err)
                  this.commitDisabled = false
                })
            } else {
              this.handleCreate()
            }
          } else {
            this.commitDisabled = false
          }
        })
      }
    },
    //新建
    handleCreate() {
      let form = this.formData
      form['@id'] = '100000'
      form['@type'] = 'EmployeeAdd'
      form['pos_x'] = ''
      form['pos_y'] = ''
      let obj = {
        request: form,
      }
      dataflow(obj).then((res) => {
        if (res.status == 200) {
          this.handleClose()
          this.$store.dispatch('initUser')
          this.$emit('clearTableData')
        }
      })
    },
    // 关闭或取消
    handleClose() {
      this.$emit('update:open', false)
    },
    // 监听鼠标事件
    clickEvent(e) {
      var box = document.getElementsByClassName(
        `default-select-tree ${this.showTree}`
      )[0]
      if (box && !box.contains(e.target)) {
        this.showTree = ''
      }
    },
    // //添加电话按钮
    // addTel() {
    //   this.formData.device.push({ deviceType: '', deviceTel: '' })
    // },
    change(e) {
      this.$forceUpdate()
    },
    //获取职务下拉框
    handleGetDuty() {
      let _this = this
      getDuty().then((res) => {
        _this.dutyOption = res.data.eventdata
      })
    },
    changeInput(e) {
      this.formData = { ...this.formData }
    },
  },
  mounted() {
    // SDK.setEvent(this.event)
    this.handleGetDuty()
    this.$nextTick(() => {
      document.addEventListener('click', this.clickEvent, true)
      //判断是否直接进如编辑或详情页
      if (this.editFlag) {
        this.handleEdit(!this.editFlag)
      }
    })
  },
  destroyed() {
    document.removeEventListener('click', this.clickEvent, true)
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/employee_dialog.scss';
</style>


